//
//  PerfectInfoController.m
//  MIDI
//
//  Created by 邵子凡 on 15/11/24.
//  Copyright © 2015年 QXSX. All rights reserved.
//

#import "PerfectInfoController.h"
#import "AddHeadPictureCell.h"
#import "AddModifyHeadCell.h"
#import "AddPerfectInfoLineCell.h"
#import "AddSameCell.h"
#import "AddPickerLabelCell.h"
#import "AppConfig.h"
#import "AddSexPickerView.h"
#import "UIView+Extension.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIActionSheet+Blocks.h"
#import "CommFunc.h"
#import "MBProgressHUD+YC.h"
#import "AddCoverView.h"
#import "QXNetWorkTool.h"
#import "APIAdress.h"
#import "UserDataSingleton.h"
#import "SelfInfoModel.h"
#import "UIImageView+WebCache.h"
#import "CommFunc.h"
#import "SelectSexViewControl.h"
#import "AddHeadImageCell.h"

@interface PerfectInfoController ()<UITableViewDelegate,UITableViewDataSource,AddSexPickerViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,UITextFieldDelegate, QXNetWorkToolDelegate, SelectSexViewDeletage, AddHeadImageCellDelegate>
{
    UITextView *_textEditor;
    UIActionSheet *myActionSheet;
    NSString *filePath;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) UIButton *sexBtn;
@property (copy, nonatomic) NSString *sexLabel;
@property (strong, nonatomic) AddPickerLabelCell *addPickerLabelCell;
@property (strong , nonatomic) UIImagePickerController *headPicker;
@property (weak, nonatomic) UIImageView *mainIconUIIamge;
@property (copy , nonatomic) NSString * imageData;
//@property (strong, nonatomic) AddHeadPictureCell *addHeadPictureCell;

@property (strong, nonatomic) AddHeadImageCell *addHeadPictureCell;

@property (strong , nonatomic) NSMutableDictionary * infoDic;

@property (copy , nonatomic) NSString *idNum;
@property (copy , nonatomic) NSString *sex;
@property (copy , nonatomic) NSString *national;
@property (copy , nonatomic) NSString *people;
@property (copy , nonatomic) NSString *birthday;

@end

@implementation PerfectInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //设置导航
    [self settingNavigation];
    
    self.imageData = @"";
    self.infoDic = [[NSMutableDictionary alloc]init];
    
    self.idNum = @"";
    self.sex = @"";
    self.national = @"";
    self.people = @"";
    self.birthday = @"";

    [self reqSelfInfo];
}

- (void)settingNavigation{
    
    //设置导航栏标题
    self.navigationItem.title = @"完善个人信息";
    
    //设置导航栏标题字体颜色（字体大小也可以在这里设置）
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [rightBtn setTitleColor:UIColorRGBA(19, 208, 202, 1) forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(saveBotton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = rightItem;
    
    //设置导航栏左边返回按钮
    [self settingLeftBarButtonItem];
    
}
//保存按钮事件实现
- (void)saveBotton:(id)sender{

    if (![CommFunc validateIDCardNumber:self.idNum])
    {
        [MBProgressHUD showError:@"请输入正确的身份证号"];
        return;
    }
    
    if ([self.national isEqualToString:@""])
    {
        [MBProgressHUD showError:@"请输入正确的国家"];
        return;
    }

    if ([self.people isEqualToString:@""])
    {
        [MBProgressHUD showError:@"请输入正确的名族"];
        return;
    }
    
    if ([self.birthday isEqualToString:@""])
    {
        [MBProgressHUD showError:@"请输入你的出生日期"];
        return;
    }
    
    UserDataSingleton *userData = [UserDataSingleton shareInstance];
    if(![userData isLogin])
    {
        [userData pleaseLogin:self];
        return;
    }
    
    NSMutableDictionary * dic = self.infoDic;
    [dic removeAllObjects];
    
    UserDataSingleton *userdata = [UserDataSingleton shareInstance];
    
    [dic setValue:userdata.real_name forKey:@"real_name"];
    [dic setValue:userdata.user_id forKey:@"user_id"];
    [dic setValue:userdata.nickname forKey:@"nickname"];
    [dic setValue:userdata.eamil forKey:@"eamil"];
    [dic setValue:self.idNum forKey:@"id_card"];
    [dic setValue:userdata.province forKey:@"province"];
    [dic setValue:userdata.curCityId forKey:@"city"];
    [dic setValue:userdata.phone forKey:@"phone"];
    [dic setValue:self.national forKey:@"nationality"];
    [dic setValue:userdata.sex forKey:@"sex"];
    [dic setValue:userdata.birthday forKey:@"birthday"];
    [dic setValue:self.people forKey:@"people"];
    
    UIImage *tmpImage = self.addHeadPictureCell.headImage.image;
    
    if (tmpImage)
    {
        [dic setValue:[CommFunc getImageBase64String:tmpImage] forKey:@"head_img"];
    }
    else
    {
        [dic setValue:@"" forKey:@"head_img"];
    }
    
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
    
    tool.QXNetWorkDelegate = self;

    [tool GetDataFromServerWithPostMethodandInterfaceName:FillDetailInterface andParameter:@[dic] tag:1];
}

//请求个人数据
-(void)reqSelfInfo
{
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
    
    tool.QXNetWorkDelegate = self;

    UserDataSingleton *userdata = [UserDataSingleton shareInstance];
    [tool GetDataFromServerWithPostMethodandInterfaceName:GetSelfInfoInterface andParameter:@[@{@"user_id":userdata.user_id}] tag:2];
}


#pragma mark QxWorkTool ------------------------
-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    if(tag == 1)
    {
        [MBProgressHUD showSuccess:@"保存成功"];
        UserDataSingleton *userdata = [UserDataSingleton shareInstance];
        userdata.isSelfInfoChange = YES;
        userdata.people = [self.infoDic objectForKey:@"people"];
        userdata.nationality = [self.infoDic objectForKey:@"nationality"];
        
        [[UserDataSingleton shareInstance] clearLocalHeadImage];
        
        [self reqSelfInfo];
    }
    else if(tag == 2)
    {
        SelfInfoModel * data = nil;
        for(NSDictionary * dic in Response)
        {
            data = [SelfInfoModel MyModelWithDict:dic];
            break;
        }
        if(data == nil)
            return;
        UserDataSingleton *userdata = [UserDataSingleton shareInstance];
        userdata.isGotSelfInfo = YES;
        userdata.midi_id = data.midi_id;
        userdata.sex = data.sex;
        userdata.eamil = data.eamil;
        userdata.people = data.people;
        userdata.nationality = data.nationality;
        userdata.id_card = [data.id_card uppercaseString];
        userdata.head_img = data.head_img;
        userdata.nickname = data.nickname;
        userdata.real_name = data.real_name;
        userdata.phone = data.phone;
        userdata.birthday = data.birthday;
        userdata.isSelfInfoChange = NO;
        [self.tableView reloadData];
    }
}

-(void)GetFailResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 7;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
        return [CommFunc getMyselfHeadCellHeight];
        
    }
//    else if (indexPath.row == 1){
//        
//        return 50;
//        
//    }
//    else if (indexPath.row == 2){
//        
//        return 12;
//        
//    }
    else if (indexPath.row == 1){
        
        return 50;
        
    }else if (indexPath.row == 2){
        
        return 50;
        
    }else if (indexPath.row == 3){
        
        return 50;
        
    }else if (indexPath.row == 4){
        
        return 50;
        
    }else if (indexPath.row == 5){
        
        return 12;
        
    }else if (indexPath.row == 6){
        
        return 50;
        
    }
    
    return 1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UserDataSingleton *userdata = [UserDataSingleton shareInstance];
    
    self.national = userdata.nationality;
    self.people = userdata.people;
    
    NSString *year;
    NSString *month;
    NSString *day;
    
    if([CommFunc validateIDCardNumber:userdata.id_card])
    {
        self.idNum = userdata.id_card;
        if(self.idNum.length == 15)
        {
            year =[@"19" stringByAppendingString:[self.idNum substringWithRange:NSMakeRange(6, 2)]];
            month = [self.idNum substringWithRange:NSMakeRange(8, 2)];
            day = [self.idNum substringWithRange:NSMakeRange(10, 2)];
            self.sex = [self.idNum substringWithRange:NSMakeRange(12, 3)];
        }
        else if(self.idNum.length == 18)
        {
            year =[self.idNum substringWithRange:NSMakeRange(6, 4)];
            month = [self.idNum substringWithRange:NSMakeRange(10, 2)];
            day = [self.idNum substringWithRange:NSMakeRange(12, 2)];
            self.sex = [self.idNum substringWithRange:NSMakeRange(14, 3)];
        }
        if([self.sex integerValue] % 2 == 0)  //判断性别
        {
            self.sex = @"女";
        }
        else
        {
            self.sex = @"男";
        }
        
        self.birthday = [[[[year stringByAppendingString:@"-"] stringByAppendingString:month]stringByAppendingString:@"-"] stringByAppendingString:day];
    }
    else
    {
        self.idNum = @"";
        self.birthday = @"";
        if(userdata.sex != nil && ([userdata.sex isEqual:@"1"] || [userdata.sex isEqual:@"2"]))
        {
            if([userdata.sex isEqual:@"1"])
            {
                self.sex = @"男";
            }
            else
            {
                self.sex = @"女";
            }
        }
        else
        {
            self.sex = @"";
        }
    }
    
    if (indexPath.row == 0) {

        self.addHeadPictureCell = [AddHeadImageCell cellWithTableView:tableView];

        [self.addHeadPictureCell hideArrow];
        
        return self.addHeadPictureCell;
        
    }
//    else if (indexPath.row == 1){
//        
//        AddModifyHeadCell *cell = [AddModifyHeadCell cellWithTableView:tableView];
//        
//        return cell;
//        
//    }
//    else if (indexPath.row == 2){
//        
//        AddPerfectInfoLineCell *cell = [AddPerfectInfoLineCell cellWithTableView:tableView];
//        
//        return cell;
//        
//    }
    else if (indexPath.row == 1){
        
        AddSameCell *cell = [AddSameCell cellWithTableView:tableView];
        cell.ID_TextField.tag = 1;
        cell.ID_TextField.delegate = self;
        cell.ID_Label.text = @"身份证号";
        
        if ([self.idNum isEqualToString:@""])
        {
            cell.ID_TextField.placeholder = @"请输入你的身份证号";
        }
        cell.ID_TextField.text = self.idNum;
        
        return cell;
        
    }else if (indexPath.row == 2){
        
        self.addPickerLabelCell = [AddPickerLabelCell cellWithTableView:tableView];
    
        self.addPickerLabelCell.showSex.text = self.sex;

        return self.addPickerLabelCell;
        
    }else if (indexPath.row == 3){
        
        AddSameCell *cell = [AddSameCell cellWithTableView:tableView];
        cell.ID_TextField.tag = 2;
        cell.ID_TextField.delegate = self;
        cell.ID_Label.text = @"国籍";
        cell.ID_TextField.placeholder = @"请输入你的国籍";
        
        cell.ID_TextField.text = self.national;
        
        return cell;
        
    }else if (indexPath.row == 4){
        
        AddSameCell *cell = [AddSameCell cellWithTableView:tableView];
        cell.ID_TextField.tag = 3;
        cell.ID_TextField.delegate = self;
        cell.ID_Label.text = @"民族";
        cell.ID_TextField.placeholder = @"请输入你的民族";
        
        cell.ID_TextField.text = self.people;
        
        return cell;
        
    }else if (indexPath.row == 5){
        
        AddPerfectInfoLineCell *cell = [AddPerfectInfoLineCell cellWithTableView:tableView];
        
        return cell;
        
    }else if (indexPath.row == 6){
        
        AddSameCell *cell = [AddSameCell cellWithTableView:tableView];
        cell.ID_TextField.tag = 4;
        cell.ID_TextField.delegate = self;
        cell.ID_Label.text = @"出生日期";
        
        if ([self.birthday isEqualToString:@""])
        {
            cell.ID_TextField.placeholder = @"请输入你的出生日期";
        }
        
        cell.ID_TextField.text = self.birthday;
        
        return cell;
        
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    if (indexPath.row == 0) {
//        
//        myActionSheet = [[UIActionSheet alloc]
//                         initWithTitle:nil
//                         delegate:self
//                         cancelButtonTitle:@"取消"
//                         destructiveButtonTitle:nil
//                         otherButtonTitles:@"打开照相机", @"从手机相册获取", nil];
//        [myActionSheet showInView:self.view];
//        
//        
//    }
//    
    if (indexPath.row == 2)
    {    
        SelectSexViewControl *obj = [SelectSexViewControl create];
        obj.view.backgroundColor = [UIColor clearColor];
        obj.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        obj.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        obj.definesPresentationContext = YES;
        obj.deletage = self;
        
        [self presentViewController:obj animated:YES completion:nil];
    }
}

//弹出view的性别选择器的button属性
- (void)uploadSexLabel:(UIButton *)sexBtn{
    
    self.sexBtn = sexBtn;
    
    switch (self.sexBtn.tag) {
        case 1:
            
            self.addPickerLabelCell.showSex.text = self.sexBtn.titleLabel.text;
            
            break;
            
        case 2:
            
            self.addPickerLabelCell.showSex.text = self.sexBtn.titleLabel.text;
            
            break;
            
        default:
            break;
    }
    
}

- (void)uploadHeadImageBtn
{
    myActionSheet = [[UIActionSheet alloc]
                     initWithTitle:nil
                     delegate:self
                     cancelButtonTitle:@"取消"
                     destructiveButtonTitle:nil
                     otherButtonTitles:@"打开照相机", @"从手机相册获取", nil];
    [myActionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == myActionSheet.cancelButtonIndex) {
        NSLog(@"取消");
    }
    
    switch (buttonIndex) {
        case 0:
            [self takePhoto];
            break;
            
        case 1:
            [self LocalPhoto];
            break;
    }
}

//打开相机
- (void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:^{
            NSLog(@"OK");
        }];
    }
    else {
        NSLog(@"模拟其中无法打开照相机，请在真机中使用");
    }
}

//读取相册
- (void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:^{
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image;
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        
        image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        
        [self.addHeadPictureCell.headImage setImage:image];
        
        self.addHeadPictureCell.headImage.contentMode = UIViewContentModeScaleToFill;
        
        [picker dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark ---UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    switch (textField.tag) {
        case 1:
            
            textField.text = [textField.text uppercaseString];
            
            if (![CommFunc validateIDCardNumber:textField.text])
            {
                [MBProgressHUD showError:@"请输入正确的身份证号"];
                
                self.idNum = @"";
            }
            else
            {
                self.idNum = textField.text;
            }
            
            break;
            
        case 2:
            
            if (textField.text == nil || [textField.text isEqualToString:@""])
            {
                [MBProgressHUD showError:@"请输入正确的国家"];
                self.national = @"";
            }
            else
            {
                self.national = textField.text;
            }
            
            break;
            
        case 3:
            
            if (textField.text == nil || [textField.text isEqualToString:@""])
            {
                self.people = @"";
                [MBProgressHUD showError:@"请输入正确的名族"];
            }
            else
            {
                self.people = textField.text;
            }
            
            break;
            
        case 4:
            
            if (textField.text == nil || [textField.text isEqualToString:@""])
            {
                self.birthday = @"";
                [MBProgressHUD showError:@"请输入你的出生日期"];
            }
            else
            {
                self.birthday = textField.text;
            }
            
            break;
            
        default:
            break;
    }
}

-(void)sex:(NSString*)s
{
    self.sex = s;
    self.addPickerLabelCell.showSex.text = s;
}

@end











